#!/usr/bin/env python2.6

import ftplib
import optparse
import os
import sys

from ftplib import FTP as ftpclient

from venya.lib import cmdparser
from venya.lib import sql

import pkgdb

class pkgsearch(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-u", "--update", action = "store_true",
            help = "Update the package information database", default = False,
            dest = "update"),
         optparse.make_option("-c", "--create", action = "store_true",
            help = "Create/Initialize package information database",
            default = False, dest = "create"),
         optparse.make_option("-d", "--database", type = "str",
            help = "SQLite database to use, default: pkginfo.db",
            default = "pkginfo.db", dest = "database"),
         ) + cmdparser.GetOpt.option_list

   help = """

   Package information database, uses ftp library to get information about
   OpenBSD packages and stores them in a SQLite database

   Uses SQLAlchemy and regex"

   """

   def __init__(self, **kwargs):
      super(pkgsearch, self).__init__(**kwargs)
      self._sql = None
      self._ftp = None

   def handle(self):
      (options, args) = self.parse()

      self._sql = sql.sqlite(options.database, bool(options.verbosity))
      pkgtable = None
      for table in self._sql.inspect():
         if str(table) == "pkg_info":
            pkgtable = table

      if options.create:
         yes = False
         if os.path.exists(options.database):
            prompt = raw_input("Are you sure about nuking the database? ")
            if (prompt.lower() == "yes") or (prompt.lower() == "y"):
               yes = True
         else:
            yes = True

         try:
            if yes:
               pkgdb.create(self._sql.engine)
         except sql.SQLError as err:
            self.error(unicode(err.message))
         except pkgdb.ModelError as err:
            self.error(unicode(err.message))

      if options.create or options.update:
         try:
            self._ftp = ftpclient("ftp.openbsd.org")
            self._ftp.login()
            self._ftp.retrbinary('RETR ports/INDEX', open('INDEX', 'wb').write)
         except ftplib.error_reply as err:
            self.error(unicode(err.message))
         except ftplib.error_temp as err:
            self.error(unicode(err.message))
         except ftplib.error_perm as err:
            self.error(unicode(err.message))
         except ftplib.error_proto as err:
            self.error(unicode(err.message))
         else:
            self._ftp.close()

         filename = "INDEX"
         fh = None
         try:
            fh = open(filename, "r")
         except IOError as err:
            self.error(unicode(err.message))
         else:
            for lines in fh.readlines():
               temp = lines.strip().split("|")
               package = temp[0]
               location = temp[1].split("/")[0]
               info = temp[3]
               maint = temp[5]
               tags = temp[6]
               version = package.split("-")[-1]

               if pkgtable:
                  pkgtable.query.filter(

               try:
                  table = pkgdb.PkgInfo(package, version, location, maint,
                        info, tags)
                  self._sql.add(table, commit = True)
               except sql.SQLError as err:
                  self.error(unicode(err.message))
               else:
                  print table, table.update



if __name__ == "__main__":
   srchpkg = None
   try:
      srchpkg = pkgsearch(version = 1.0, args = sys.argv, usage = "package")
      if len(srchpkg) <= 1:
         srchpkg.printhelp()
      else:
         srchpkg.handle()
   except cmdparser.GetOptError as err:
      print err.message
      sys.exit(1)

